from fastapi import APIRouter, Depends, HTTPException, Request, Query
from fastapi.responses import JSONResponse
from sqlalchemy import and_
from sqlalchemy.orm import Session
import logging
import time

from app.db.session import get_db
from app.models.models import InternalVideo, InternalJob, InternalUser, InternalVoice
from app.services.external_api_v2 import create_digital_person_v2, create_videomix_v2, create_voice_clone_v2
from app.core.config import settings
from app.core.logging_config import get_internal_logger
from app.core.utils import decode_token, get_token

# 获取内部API专用日志记录器
internal_logger = get_internal_logger()

router = APIRouter()

# 内部创建数字人接口（无需认证，使用V2外部接口）
@router.post("/internal/video/create")
async def internal_create_digital_human(request: Request, db: Session = Depends(get_db)):
    """
    内部创建数字人接口（无需token验证，使用V2外部接口）
    """
    request_id = f"INTERNAL_VIDEO_CREATE_{int(time.time() * 1000)}"
    internal_logger.info(f"[{request_id}] ===== 内部数字人创建请求开始 =====")
    internal_logger.info(f"[{request_id}] 收到请求：{request.method} {request.url.path}")
    internal_logger.info(f"[{request_id}] 客户端IP: {request.client.host if request.client else 'Unknown'}")

    # 获取请求头中的token
    try:
        token = get_token(request)
    except HTTPException as e:
        internal_logger.error(f"[{request_id}] 获取token失败: {e}")
        return JSONResponse(status_code=400, content={'error': f'获取token失败：{e}'})
    
    # 解码token
    try:
        decoded_token = decode_token(token)
        internal_logger.info(f"[{request_id}] 解码token成功: {decoded_token}")
    except Exception as e:
        internal_logger.error(f"[{request_id}] 解码token失败: {e}")
        return JSONResponse(status_code=400, content={'error': f'token解码失败：{e}'})
    
    
    try:
        data = await request.json()
        video_url = data.get('video_url')
        title = data.get('title')
        name_id = decoded_token.get('uid')

        # 判断缺少哪个参数
        if not video_url:
            internal_logger.error(f"[{request_id}] 缺少必要参数: video_url")
            return JSONResponse(status_code=400, content={'error': 'video_url is required'})
        if not title:
            internal_logger.error(f"[{request_id}] 缺少必要参数: title")
            return JSONResponse(status_code=400, content={'error': 'title is required'})
        if not name_id:
            internal_logger.error(f"[{request_id}] 缺少必要参数: name_id")
            return JSONResponse(status_code=400, content={'error': 'name_id is required'})

        
        # 检查内部用户是否存在，不存在则创建
        user = db.query(InternalUser).filter(InternalUser.name_id == name_id).first()
        if not user:
            new_user = InternalUser(name_id=name_id)
            db.add(new_user)
            db.commit()
            db.refresh(new_user)
            internal_logger.info(f"[{request_id}] 创建内部用户: {name_id}")
        else:
            internal_logger.info(f"[{request_id}] 用户已存在: {name_id}")

        # 构建V2外部API调用数据
        external_data = {
            'name': title,
            'url': video_url,
            'callback': f"{settings.INTERNAL_VIDEO_CALLBACK_URL}"
        }

        internal_logger.info(f"[{request_id}] 调用V2外部API创建数字人: {external_data}")

        # 调用V2版本的外部 API 创建数字人
        try:
            response_data, status_code = await create_digital_person_v2(external_data)
            internal_logger.info(f"[{request_id}] V2外部API响应：状态码={status_code}, 数据={response_data}")
            # 获取外部API返回的jobId作为voice_id
            job_id = response_data.get('data', {}).get('jobId')
            if not job_id:
                internal_logger.error(f"[{request_id}] 创建数字人微服务未返回jobId，响应数据: {response_data}")
                return JSONResponse(status_code=400, content={'error': 'Create digital human service did not return jobId'})
            if status_code == 200:
                # 保存到internal_videos表
                new_video = InternalVideo(
                    name_id=name_id,
                    video_url=video_url,  # 先保存原始URL，回调时更新
                    title=title,
                    job_id=job_id
                )
                db.add(new_video)
                db.commit()
                db.refresh(new_video)
                internal_logger.info(f"[{request_id}] 微服务创建内部数字人成功: job_id={job_id}, title={title}")
                
                return JSONResponse(status_code=200, content={
                    'code': 200,
                    'message': 'Digital human created successfully',
                    'job_id': job_id
                })
            else:
                internal_logger.error(f"[{request_id}] 微服务调用V2外部API失败，状态码：{status_code}")
                return JSONResponse(status_code=status_code, content={'error': 'External API error', 'details': response_data})
                
        except Exception as api_error:
            internal_logger.error(f"[{request_id}] 微服务调用V2外部API时出错：{api_error}")
            return JSONResponse(status_code=500, content={'error': 'External API error'})

    except Exception as e:
        internal_logger.error(f"[{request_id}] 微服务创建内部数字人时出错: {e}")
        db.rollback()
        return JSONResponse(status_code=500, content={'error': f'Internal server error: {str(e)}'})

# 内部数字人回调接口
@router.post("/internal/callback/video")
async def internal_video_callback(request: Request, db: Session = Depends(get_db)):
    """
    内部数字人回调接口
    """
    request_id = f"INTERNAL_VIDEO_CALLBACK_{int(time.time() * 1000)}"
    internal_logger.info(f"[{request_id}] ===== 内部数字人回调请求开始 =====")
    internal_logger.info(f"[{request_id}] 收到请求：{request.method} {request.url.path}")
    internal_logger.info(f"[{request_id}] 客户端IP: {request.client.host if request.client else 'Unknown'}")
    
    try:
        data = await request.json()
        internal_logger.info(f"[{request_id}] 接收到的数据：{data}")
        
        # 提取必要参数
        job_id = data.get('id') # 用于微服务回调的任务ID
        status = data.get('status') # 任务状态
        video_url = data.get('url') # 数字人视频URL
        if not job_id:
            internal_logger.error(f"[{request_id}] 缺少必要参数: id")
            return JSONResponse(status_code=400, content={'error': 'id is required'})
        if not status:
            internal_logger.error(f"[{request_id}] 缺少必要参数: status")
            return JSONResponse(status_code=400, content={'error': 'status is required'})
        if not video_url:
            internal_logger.error(f"[{request_id}] 缺少必要参数: url")
            return JSONResponse(status_code=400, content={'error': 'url is required'})
        
        # 查询内部数字人记录
        video = db.query(InternalVideo).filter(InternalVideo.job_id == job_id).first()
        if not video:
            internal_logger.error(f"[{request_id}] 内部数字人记录不存在")
            return JSONResponse(status_code=404, content={'error': 'Internal digital human record not found'})
        if status == "SUCCESS":
            # 更新数字人视频URL
            video.task_finished = True
            video.video_url = video_url
            db.commit()
            db.refresh(video)
            internal_logger.info(f"[{request_id}] 内部数字人视频URL更新成功: {video_url}")
            return JSONResponse(status_code=200, content={'code': 200, 'message': 'Internal digital human video URL update successfully'})
        else:
            internal_logger.error(f"[{request_id}] 内部数字人视频URL更新失败: {video_url}")
            return JSONResponse(status_code=400, content={'error': 'Internal digital human video URL update failed'})

    except Exception as e:
        internal_logger.error(f"[{request_id}] 处理内部数字人回调时出错: {e}")
        return JSONResponse(status_code=500, content={'error': f'Internal server error: {str(e)}'})



# 内部声音克隆接口
@router.post("/internal/voice/train")
async def internal_clone_voice(request: Request, db: Session = Depends(get_db)):
    """
    V2版本 - 创建声音克隆接口
    """
    request_id = f"INTERNAL_VOICE_CLONE_{int(time.time() * 1000)}"
    internal_logger.info(f"[{request_id}] ===== 内部声音克隆创建请求开始 =====")
    internal_logger.info(f"[{request_id}] 收到请求：{request.method} {request.url.path}")
    internal_logger.info(f"[{request_id}] 客户端IP: {request.client.host if request.client else 'Unknown'}")

    # 获取token
    try:
        token = get_token(request)
    except HTTPException as e:
        internal_logger.error(f"[{request_id}] 获取token失败: {e}")
        return JSONResponse(status_code=400, content={'error': f'获取token失败：{e}'})
    
    # 解码token
    try:
        decoded_token = decode_token(token)
        internal_logger.info(f"[{request_id}] 解码token成功: {decoded_token}")
    except Exception as e:
        internal_logger.error(f"[{request_id}] 解码token失败: {e}")
        return JSONResponse(status_code=400, content={'error': f'token解码失败：{e}'})
    
    
    # 记录请求头
    headers_dict = dict(request.headers)
    internal_logger.info(f"[{request_id}] 请求头: {headers_dict}")

    # 验证 Content-Type
    if request.headers.get('content-type') != 'application/json':
        internal_logger.error(f"[{request_id}] Content-Type 非 application/json")
        return JSONResponse(status_code=400, content={'error': f'Content-Type must be application/json: {e}'})

    # 解析 JSON 数据
    try:
        data = await request.json()
        internal_logger.info(f"[{request_id}] 接收到的数据：{data}")
    except Exception as e:
        internal_logger.error(f"[{request_id}] 请求体中缺少 JSON 数据：{e}")
        return JSONResponse(status_code=400, content={'error': f'Missing JSON data in request body: {e}'})

    # 提取参数
    name_id = decoded_token.get('uid')
    audio_url = data.get('audio_url')
    title = data.get('title')
    voice_type = data.get('voiceType', settings.EXTERNAL_VOICE_V2_TYPE)  # 可选参数，使用配置默认值

    internal_logger.info(f"[{request_id}] 解析参数 - name_id: {name_id}, audio_url: {audio_url}, title: {title}, voiceType: {voice_type}")

    if not all([name_id, audio_url, title]):
        internal_logger.error(f"[{request_id}] 缺少必要参数")
        return JSONResponse(status_code=400, content={'error': 'name_id, audio_url, title are required'})

    # 检查用户是否存在，不存在则创建
    user = db.query(InternalUser).filter(InternalUser.name_id == name_id).first()
    if not user:
        internal_logger.info(f"[{request_id}] 用户不存在，自动为其创建用户记录，name_id={name_id}")
        internal_logger.info(f"[{request_id}] 创建新用户: {name_id}")
        user = InternalUser(name_id=name_id)
        db.add(user)
        db.commit()
        db.refresh(user)
        internal_logger.info(f"[{request_id}] 已创建新用户，name_id={user.name_id}")
    else:
        internal_logger.info(f"[{request_id}] 用户已存在: {name_id}")

    # 构建外部API调用数据
    external_data = {
        'name': title,
        'url': audio_url,
        'voiceType': voice_type,
        'callback': f"{settings.INTERNAL_VOICE_CALLBACK_URL}"
    }
    internal_logger.info(f"[{request_id}] 构建外部API调用数据: {external_data}")

    # 调用V2版本的外部 API 创建声音克隆
    try:
        internal_logger.info(f"[{request_id}] 开始调用V2声音克隆API")
        internal_logger.info(f"[{request_id}] API地址: {settings.EXTERNAL_VOICE_V2_URL}")
        internal_logger.info(f"[{request_id}] 发送数据: {external_data}")
        
        response_data, status_code = await create_voice_clone_v2(external_data)
        
        internal_logger.info(f"[{request_id}] V2声音克隆API响应：状态码={status_code}, 数据={response_data}")
        
        if status_code == 200:
            # 如果外部API调用成功，将任务信息保存到数据库
            try:
                # 获取外部API返回的jobId作为voice_id
                job_id = response_data.get('data', {}).get('jobId')
                if not job_id:
                    internal_logger.error(f"[{request_id}] 微服务未返回jobId，响应数据: {response_data}")
                    return JSONResponse(status_code=400, content={'error': 'External API did not return jobId'})
                
                internal_logger.info(f"[{request_id}] 获取到jobId: {job_id}")
                
                # 创建声音记录（临时状态，等待回调更新）
                # 注意：如果数据库中还没有task_id字段，需要先执行SQL脚本添加字段
                try:
                    new_voice = InternalVoice(
                        name_id=name_id,
                        title=title,
                        audio_url=audio_url,  # 先保存原始URL，回调时可能更新
                        job_id=job_id,  # 保存taskId用于回调通知
                    )
                    db.add(new_voice)
                    db.commit()
                    db.refresh(new_voice)
                    internal_logger.info(f"[{request_id}] V2声音记录已保存到数据库 - 用户: {name_id}, 标题: {title}, JobID: {job_id}, VoiceType: {voice_type}, 声音ID: {new_voice.id}")
                    
                except Exception as e:
                    internal_logger.error(f"[{request_id}] 保存到数据库时出错：{e}")            
                    db.rollback()
                    return JSONResponse(status_code=500, content={'error': 'Database error'})
            
            except Exception as e:
                internal_logger.error(f"[{request_id}] 外层异常处理，保存到数据库时出错：{e}")
                db.rollback()
                return JSONResponse(status_code=500, content={'error': 'Database error'})
            
            internal_logger.info(f"[{request_id}] ===== V2声音克隆请求成功完成 =====")
            return JSONResponse(status_code=200, content={'code': 200, 'message': 'Voice clone creation started', 'data': {'jobId': job_id}})
        else:
            internal_logger.error(f"[{request_id}] V2声音克隆API请求失败，状态码：{status_code}")
            return JSONResponse(status_code=status_code, content=response_data)
            
    except Exception as e:
        internal_logger.error(f"[{request_id}] 调用V2声音克隆API时出错：{e}")
        return JSONResponse(status_code=500, content={'error': 'External API error'})

# 内部回调接口用于更新声音克隆任务状态
@router.post("/internal/callback/voice")
async def internal_voice_callback(request: Request, db: Session = Depends(get_db)):
    """
    内部回调接口用于更新声音克隆任务状态
    """
    request_id = f"INTERNAL_VOICE_CALLBACK_{int(time.time() * 1000)}"
    internal_logger.info(f"[{request_id}] ===== 内部声音克隆回调请求开始 =====")
    internal_logger.info(f"[{request_id}] 收到请求：{request.method} {request.url.path}")
    internal_logger.info(f"[{request_id}] 客户端IP: {request.client.host if request.client else 'Unknown'}")

    try:
        data = await request.json()
        internal_logger.info(f"[{request_id}] 接收到的数据：{data}")
        
        # 提取必要参数
        title = data.get('name') # 用户ID
        job_id = data.get('id') # 用于微服务回调的任务ID
        voice_id = data.get('tid')
        status = data.get('status') # 任务状态
        # 判断缺少哪个参数
        if not title:
            internal_logger.error(f"[{request_id}] 缺少必要参数: name")
            return JSONResponse(status_code=400, content={'error': 'name is required'})
        if not job_id:
            internal_logger.error(f"[{request_id}] 缺少必要参数: job_id")
            return JSONResponse(status_code=400, content={'error': 'job_id is required'})
        if not status:
            internal_logger.error(f"[{request_id}] 缺少必要参数: status")
            return JSONResponse(status_code=400, content={'error': 'status is required'})
        if not voice_id:
            internal_logger.error(f"[{request_id}] 缺少必要参数: tid")
            return JSONResponse(status_code=400, content={'error': 'tid is required'})
        
        # 更新声音克隆任务状态
        voice = db.query(InternalVoice).filter(InternalVoice.job_id == job_id).first()
        if not voice:
            internal_logger.error(f"[{request_id}] 声音克隆任务不存在")
            return JSONResponse(status_code=404, content={'error': 'Voice clone task not found'})
        try:
            if status == "SUCCESS":
                # 更新任务状态
                voice.task_finished = True
                voice.voice_id = voice_id
                db.commit()
                db.refresh(voice)
                internal_logger.info(f"[{request_id}] 声音克隆任务状态更新成功")
            else:
                internal_logger.error(f"[{request_id}] 声音克隆任务状态更新失败")
                return JSONResponse(status_code=500, content={'error': 'Voice clone task status update failed'})
        except Exception as e:
            # 回滚
            db.rollback()
            internal_logger.error(f"[{request_id}] 更新声音克隆任务状态时出错: {e}")
            return JSONResponse(status_code=500, content={'error': f'Internal server error: {str(e)}'})
            
        return JSONResponse(status_code=200, content={'code': 200, 'message': 'Voice clone task status updated successfully'})
        
    except Exception as e:
        internal_logger.error(f"[{request_id}] 处理内部声音克隆回调时出错: {e}")
        return JSONResponse(status_code=500, content={'error': f'Internal server error: {str(e)}'})
        
# 内部创建作品接口（无需认证，使用V2外部接口）
@router.post("/internal/task/create")
async def internal_create_task(request: Request, db: Session = Depends(get_db)):
    """
    内部创建作品接口（无需token验证，使用V2外部接口进行作品合成）
    """
    request_id = f"INTERNAL_TASK_CREATE_{int(time.time() * 1000)}"
    internal_logger.info(f"[{request_id}] ===== 内部任务创建请求开始 =====")
    internal_logger.info(f"[{request_id}] 收到请求：{request.method} {request.url.path}")
    internal_logger.info(f"[{request_id}] 客户端IP: {request.client.host if request.client else 'Unknown'}")

    # 获取token
    try:
        token = get_token(request)
    except HTTPException as e:
        internal_logger.error(f"[{request_id}] 获取token失败: {e}")
        return JSONResponse(status_code=400, content={'error': f'获取token失败：{e}'})
    
    # 解码token
    try:
        decoded_token = decode_token(token)
        internal_logger.info(f"[{request_id}] 解码token成功: {decoded_token}")
    except Exception as e:
        internal_logger.error(f"[{request_id}] 解码token失败: {e}")
        return JSONResponse(status_code=400, content={'error': f'token解码失败：{e}'})
    try:
        data = await request.json()
        name_id = decoded_token.get('uid') # 内部用户ID
        personUrl = data.get('video_url')  # 对应personUrl
        voice_id = data.get('voice_id')    # 用于查找speaker_id
        voice_url = data.get('audio_url')  # 对应voiceUrl
        text = data.get('text')            # 对应content
        title = data.get('title')          # 对应name
        voice_type = data.get('voice_type')  # 对应voiceType
        
        # 判断缺少哪个参数
        if not title:
            internal_logger.error(f"[{request_id}] 缺少必要参数: title")
            return JSONResponse(status_code=400, content={'error': 'title is required'})
        if not personUrl:
            internal_logger.error(f"[{request_id}] 缺少必要参数: personUrl")
            return JSONResponse(status_code=400, content={'error': 'personUrl is required'})
        
        # 检查内部用户是否存在，不存在则创建
        user = db.query(InternalUser).filter(InternalUser.name_id == name_id).first()
        if not user:
            internal_logger.info(f"[{request_id}] 创建内部用户: {name_id}")
            user = InternalUser(name_id=name_id)
            db.add(user)
            db.commit()
            db.refresh(user)
            internal_logger.info(f"[{request_id}] 已创建新用户，name_id={name_id}")
        else:
            internal_logger.info(f"[{request_id}] 用户已存在: {name_id}")

        # 通过判断body中的voice_url是否存在，来决定使用音频驱动还是文本驱动
        if voice_url: # 音频驱动
            # 如果voice_url存在，则使用音频驱动
            external_data = {
                'name': title,
                'personUrl': personUrl,  # 数字人视频URL
                'callback': f"{settings.INTERNAL_VIDEOMIX_CALLBACK_URL}",
                'voiceUrl': voice_url
            }
            internal_logger.info(f"[{request_id}] 使用音频驱动: {external_data}")
        else: # 文本驱动
            # 如果voice_url不存在，则使用文本驱动
            voice_id = str(voice_id)
            external_data = {
                'name': title,
                'personUrl': personUrl,  # 数字人视频URL
                'callback': f"{settings.INTERNAL_VIDEOMIX_CALLBACK_URL}",
                'voiceTid': voice_id,  # 使用voiceUrl参数传递音频文件URL
                'content': text,
                'voiceType': 'lite'  # 使用lite声音类型
            }
            internal_logger.info(f"[{request_id}] 使用文本驱动: {external_data}")

        # 调用V2版本的外部 API 创建作品
        try:
            response_data, status_code = await create_videomix_v2(external_data)
            internal_logger.info(f"[{request_id}] V2外部API响应：状态码={status_code}, 数据={response_data}")
            if status_code == 200:
                # 获取外部API返回的jobId作为voice_id
                job_id = response_data.get('data', {}).get('jobId')
                if not job_id:
                    internal_logger.error(f"[{request_id}] 缺少必要参数: jobId")
                    return JSONResponse(status_code=400, content={'error': 'jobId is required'})
                # 保存到internal_jobs表
                new_job = InternalJob(
                    name_id=name_id,
                    job_id=job_id,
                    title=title,
                    only_generate_audio=False,  # V2版本生成视频
                    personUrl=personUrl,
                    video_url=None,
                    voice_id=voice_id,
                    text=text
                )
                db.add(new_job)
                db.commit()
                db.refresh(new_job)
                # V2使用回调机制，无需启动轮询监控
                internal_logger.info(f"[{request_id}] 内部任务创建成功, job_id={job_id}")
                
                return JSONResponse(status_code=200, content={'code': 200, 'job_id': job_id, 'message': '任务已提交，等待处理完成'})
            else:
                # 回滚
                db.rollback()
                internal_logger.error(f"[{request_id}] V2外部API调用失败，状态码：{status_code}")
                return JSONResponse(status_code=status_code, content={'error': 'External API error', 'details': response_data})
                
        except Exception as api_error:
            internal_logger.error(f"[{request_id}] 调用V2外部API时出错：{api_error}")
            return JSONResponse(status_code=400, content={'error': 'External API error'})
            
    except Exception as e:
        internal_logger.error(f"[{request_id}] 创建内部任务时出错: {e}")
        db.rollback()
        return JSONResponse(status_code=500, content={'error': f'Internal server error: {str(e)}'})
    
# 内部创建作品回调接口
@router.post("/internal/callback/videomix")
async def internal_videomix_callback(request: Request, db: Session = Depends(get_db)):
    """
    内部创建作品回调接口
    """
    request_id = f"INTERNAL_VIDEOMIX_CALLBACK_{int(time.time() * 1000)}"
    internal_logger.info(f"[{request_id}] ===== 内部作品回调请求开始 =====")
    internal_logger.info(f"[{request_id}] 收到请求：{request.method} {request.url.path}")
    try:
        data = await request.json()
        job_id = data.get('id')
        status = data.get('status')
        video_url = data.get('url')
        
        if not job_id:
            internal_logger.error(f"[{request_id}] 内部创建作品缺少必要参数: id")
            return JSONResponse(status_code=400, content={'error': 'id is required'})
        if not status:
            internal_logger.error(f"[{request_id}] 内部创建作品缺少必要参数: status")
            return JSONResponse(status_code=400, content={'error': 'status is required'})
        if not video_url:
            internal_logger.error(f"[{request_id}] 内部创建作品缺少必要参数: url")
            return JSONResponse(status_code=400, content={'error': 'url is required'})
        
        # 更新内部作品状态
        job = db.query(InternalJob).filter(InternalJob.job_id == job_id).first()
        if not job:
            internal_logger.error(f"[{request_id}] 作品不存在: job_id={job_id}")
            return JSONResponse(status_code=404, content={'error': f'Job with job_id {job_id} not found'})
        
        if status == "SUCCESS":
            from app.services.huoshan_oss import upload_file
            try:
                # 更新作品状态
                job.task_finished = True
                
                db.commit()
                db.refresh(job)
                internal_logger.info(f"[{request_id}] 作品状态更新成功: job_id={job_id}, video_url={video_url}")
                import os
                # 获取视频文件名
                video_name = os.path.basename(video_url)
                # 上传视频到火山引擎
                upload_result = await upload_file(settings.OSS_VIDEO_TASK, video_name, video_url)
                if upload_result and upload_result.get('code') == 200:
                    tos_video_url = upload_result.get('oss_url')
                else:
                    tos_video_url = None
                if tos_video_url:
                    job.video_url = tos_video_url
                    job.task_finished = True
                    db.commit()
                    db.refresh(job)
                    internal_logger.info(f"[{request_id}] 视频上传成功: job_id={job_id}, video_url={video_url}")
                    return JSONResponse(status_code=200, content={'code': 200, 'message': '作品状态更新成功'})
                else:
                    internal_logger.error(f"[{request_id}] 视频上传失败: job_id={job_id}, video_url={video_url}")
                    return JSONResponse(status_code=500, content={'code': 500, 'error': f'视频上传失败'})
            except Exception as e:
                internal_logger.error(f"[{request_id}] 作品状态更新失败: job_id={job_id}, status={status}, error={e}")
                db.rollback()
                return JSONResponse(status_code=500, content={'error': f'作品状态更新失败：{e}'})
        else:
            internal_logger.error(f"[{request_id}] 微服务作品创建失败: job_id={job_id}, status={status}")
            return JSONResponse(status_code=400, content={'error': f'微服务作品创建失败'})
    except Exception as e:
        internal_logger.error(f"[{request_id}] 内部作品回调接口处理失败: {e}")
        db.rollback()
        return JSONResponse(status_code=500, content={'error': f'内部作品回调接口处理失败：{e}'})

# 查询指定用户信息的接口
@router.get("/internal/user/content")
async def get_user_content(
    name_id: str = Query(None, description="User's name_id"), # 将name_id设置成可选（因为加了token认证，所以name_id不需要传入，为了兼容以前没有登录系统的版本）
    type: int = Query(..., description="Query type: 1 for digital human, 2 for voices, 3 for jobs, 4 for V2 jobs only"),
    is_public: bool = Query(False, description="是否查询公版声音/数字人"),
    db: Session = Depends(get_db),
    request: Request = None
):
    request_id = f"INTERNAL_USER_CONTENT_{int(time.time() * 1000)}"

    # 获取token
    try:
        token = get_token(request)
        # internal_logger.info(f"[{request_id}] 获取token成功: {token}")
    except HTTPException as e:
        internal_logger.error(f"[{request_id}] 获取token失败: {e}")
        return JSONResponse(status_code=400, content={'error': f'获取token失败：{e}'})
    
    # 解码token
    try:
        decoded_token = decode_token(token)
        # internal_logger.info(f"[{request_id}] 解码token成功: {decoded_token}")
    except Exception as e:
        internal_logger.error(f"[{request_id}] 解码token失败: {e}")
        return JSONResponse(status_code=400, content={'error': f'token解码失败：{e}'})
    
    name_id = decoded_token.get('uid') # 从token中获取name_id
    try:

        if type == 1:
            if is_public:
                result = [
                    {
                        'id': 1,
                        'name_id': "public",
                        'title': "明轩",
                        'video_url': "https://xiaorui.tos-cn-beijing.volces.com/shuzhiren/30961380_1722565540160.mp4",
                    },
                    {
                        'id': 2,
                        'name_id': "public",
                        'title': "晓依",
                        'video_url': "https://xiaorui.tos-cn-beijing.volces.com/shuzhiren/17694979_1722565947110.mp4",
                    },
                ]
            else:
                # 查询 Video 表
                contents = db.query(InternalVideo).filter(and_(InternalVideo.name_id == name_id)).all()
                result = [
                    {
                        'name_id': c.name_id,
                        'video_url': c.video_url,
                        'title': c.title,
                        'id': c.id # 数字人ID
                    } for c in contents
                ]
            return JSONResponse(status_code=200, content={'code': 200, 'type': 1, 'data': result})

        elif type == 2:
            # 如果查询公版声音，则从代码中获取
            if is_public:
                try:
                    result = settings.GONGGONG_AUDIO_URL
                    return JSONResponse(
                        status_code=200,
                        content=result
                    )
                except Exception as e:
                    internal_logger.error(f"[{request_id}] 调用外部 API 获取声音列表失败: {e}")
                    return JSONResponse(
                        status_code=500,
                        content={'error': 'Failed to retrieve voice list from external API'}
                    )
            else:
                # 从本地 internal_voices 表查询用户的声音数据
                try:
                    contents = db.query(InternalVoice).filter(and_(InternalVoice.name_id == name_id)).all()
                    result = []
                    for c in contents:
                        voice_data = {
                            'voice_id': c.voice_id,
                            'title': c.title,
                            'audio_url': c.audio_url
                        }
                        result.append(voice_data)
                    
                    return JSONResponse(
                        status_code=200,
                        content={'code': 200, 'type': 2, 'data': result}
                    )
                except Exception as e:
                    logging.error(f"查询本地声音数据失败: {e}")
                    return JSONResponse(
                        status_code=500,
                        content={'error': 'Failed to retrieve local voice data'}
                    )

        elif type == 3:
            # 查询所有内部作品
            try:
                # 查询作品 (InternalJob表)
                jobs = db.query(InternalJob).filter(and_(InternalJob.name_id == name_id)).all()
                
                result = []
                
                # 处理V1作品数据
                for c in jobs:
                    if c.create_time:
                        adj_time = c.create_time
                        found_time_value = adj_time.timestamp()
                    else:
                        found_time_value = None
                    result.append({
                        'name_id': c.name_id,
                        'job_id': c.job_id,
                        'video_url': c.video_url,
                        'text': c.text,
                        'title': c.title,
                        'found_time': found_time_value,           
                    })
                
                return JSONResponse(status_code=200, content={'code': 200, 'type': 3, 'data': result})
                
            except Exception as e:
                logging.error(f"查询作品数据失败: {e}")
                return JSONResponse(
                    status_code=500,
                    content={'error': 'Failed to retrieve job data'}
                )

        else:
            return JSONResponse(status_code=400, content={'error': 'Invalid type parameter'})

    except Exception as e:
        logging.error(f"Error retrieving user content: {e}")
        return JSONResponse(status_code=500, content={'error': 'Internal server error'})